package database.didactic;

import database.ConnectionFactory;
import database.util.Queries;
import model.didactic.InformationSource;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

/**
 * Created with IntelliJ IDEA.
 * Author: Kostika Gorica
 * User:   kosta
 * Date:   1/2/13
 * Time:   12:39 AM
 */
public class InformationSourceDao {

    public static ArrayList<InformationSource> getSources(){
        ArrayList<InformationSource> result = new ArrayList<InformationSource>();
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            connection = ConnectionFactory.getConnection();
            statement = connection.createStatement();
            resultSet = statement.executeQuery(Queries.INFORMATION_SOURCES_SELECT_QUERY);
            result = toInformationSources(resultSet);
        } catch (SQLException e) {
            System.err.println("InformationSourceDao.getSources Error db");
            e.printStackTrace();
        } finally {
            try{
                if (resultSet!=null) resultSet.close();
                if (statement!=null) statement.close();
                if (connection!=null) connection.close();
            } catch (SQLException e) {
                System.err.println("InformationSourceDao.getSources finally block error");
            }
        }
        return result;
    }



    public static ArrayList<InformationSource> toInformationSources(ResultSet rs){
        ArrayList<InformationSource> result = new ArrayList<InformationSource>();

        try {
            while (rs.next()) {
                InformationSource informationSource = toInformationSource(rs);
                result.add(informationSource);
            }
        } catch (SQLException e) {
            System.err.println("toInformationSources ResultSetError");
            e.printStackTrace();
        } catch (Exception e) {
            System.err.println("toInformationSources unknown ResultSetError");
            e.printStackTrace();
        }
        return result;
    }


    private static InformationSource toInformationSource(ResultSet rs) throws SQLException {
        if (rs == null || rs.isClosed()){
            throw new SQLException("ResultSet Closed !!!");
        }
        InformationSource informationSource = new InformationSource();
        informationSource.setId(rs.getInt(1));
        informationSource.setSourceName(rs.getString(2));
        informationSource.setDescription(rs.getString(3));
        informationSource.setParentId(rs.getInt(4));

        return informationSource;
    }
}
